package com.cjh.admin.config.shiro;

import com.cjh.common.utils.StringUtil;
import com.cjh.common.service.UserService;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.credential.SimpleCredentialsMatcher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


@Component
public class MyCredenticalsMatcher extends SimpleCredentialsMatcher {

    @Autowired
    private UserService userService;

    //使用自定义token


    @Override
    public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {
        JwtToken jwtToken=(JwtToken) token;

        if (jwtToken.getPassword() == null){
            return true;
        }

        //获得用户输入的密码:(可以采用加盐(salt)的方式去检验)
        String inPassword = new String(jwtToken.getPassword());

        //获得数据库中的密码
        String username = String.valueOf(info.getPrincipals());
//        System.out.println("username:"+username);
//        System.out.println("username:"+username);f
        //获取盐
        String slat = userService.getUserByUserName(username).getSalt();
//        System.out.println("slat"+slat);
//        System.out.println("StringUtil.md5(inPassword + slat):"+StringUtil.md5(inPassword + slat));
//        System.out.println("dbPassword:"+info.getCredentials());
        String dbPassword=(String) info.getCredentials();

        //进行密码的比对
        return this.equals(StringUtil.md5(inPassword + slat), dbPassword);
    }
}
